package org.qiyu.live.im.core.server.Servicer.impl;

import com.alibaba.fastjson2.JSON;
import jakarta.annotation.Resource;
import org.apache.rocketmq.client.exception.MQBrokerException;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.client.producer.MQProducer;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.common.message.Message;
import org.apache.rocketmq.remoting.exception.RemotingException;
import org.idea.qiyu.live.framework.redis.starter.key.ImCoresServerProviderCacheKeyBuilder;
import org.qiyu.live.im.core.server.Servicer.ImMsgAckCheckServicer;
import org.qiyu.live.im.core.server.interfaces.constants.ImCoreServicerConstants;
import org.qiyu.live.im.dto.ImMsgBody;
import org.qiyu.live.im.topic.ImCoreServerProviderTopicNames;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

/**
 * @Description: //todo
 * @Author: 张广焱
 * @Date: 2023-12-11 18:52
 */
@Service
public class ImMsgAckCheckServicerImpl implements ImMsgAckCheckServicer {
    private static final Logger logger = LoggerFactory.getLogger(ImMsgAckCheckServicerImpl.class);
    @Resource
    private RedisTemplate<String, Object> redisTemplate;
    @Resource
    private MQProducer mqProducer;
    @Resource
    private ImCoresServerProviderCacheKeyBuilder cacheKeyBuilder;

    @Override
    public void doMsgAck(ImMsgBody imMsgBody) {
        redisTemplate.opsForHash().delete(cacheKeyBuilder.buildImAckMapKey(imMsgBody.getUserId(), imMsgBody.getAppId()), imMsgBody.getMsgId());
    }

    @Override
    public void recordMsgAck(ImMsgBody imMsgBody, int times) {
        redisTemplate.opsForHash().put(cacheKeyBuilder.buildImAckMapKey(imMsgBody.getUserId(), imMsgBody.getAppId()), imMsgBody.getMsgId(), times);
    }

    @Override
    public void sendDelayMsg(ImMsgBody imMsgBody) {
        String jsonString = JSON.toJSONString(imMsgBody);
        Message message = new Message();
        message.setBody(jsonString.getBytes());
        message.setTopic(ImCoreServerProviderTopicNames.QIYU_LIVE_IM_ACK_MSG_TOPIC);
        message.setDelayTimeLevel(2);
        try {
            SendResult send = mqProducer.send(message);
            logger.info("[ImMsgAckCheckServicerImpl] send is  ",send);
        } catch (Exception e) {
            logger.error("[ImMsgAckCheckServicerImpl] error is  ",e);
        }
    }

    @Override
    public int getMsgAckTimes(String msgId, long userId, int appId) {
        Object value = redisTemplate.opsForHash().get(cacheKeyBuilder.buildImAckMapKey(userId, appId), msgId);
        if (value ==null){
            return  -1;
        }
        return 0;
    }
}
